package com.lj.tools.util;

import com.lj.tools.exception.YerException;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileUtil {
    private static String baseDir = "uploads";
    private static SimpleDateFormat pathFormat = new SimpleDateFormat("yyyyMMdd");

    public static String getBaseDir(){
        return baseDir;
    }

    public static String getTempDir(){
        return baseDir+"/tmp";
    }

    public static String  getTempDirPath(){
        return String.format("%s/tmp/%s", baseDir, pathFormat.format(new Date()));
    }

    public static File getTempFile(String fileName){
        return new File(getTempDirPath()+File.separator+fileName);
    }

    public static String getFileDirPath(){
        return baseDir+"/"+pathFormat.format(new Date());
    }

    public static File getFile(String fileName){
        return new File(getFileDirPath()+"/"+fileName);
    }

    /**
     * 计算文件md5值
     * */
    public static String md5(File file) throws YerException {
        if (file == null || !file.exists()){
            throw new YerException("文件不存在");
        }
        try{
            FileInputStream inputStream = new FileInputStream(file);
            return Md5Util.toHex(Md5Util.computeMD5Hash(inputStream));
        }catch (Exception e){
            throw new YerException(e.getMessage());
        }
    }

    public static String getExtension(File file){
        return getExtension(file.getName());
    }

    public static String getExtension(String file){
        int pos = file.lastIndexOf(".");
        if (pos == -1){
            return null;
        }
        return file.substring(pos);
    }

    /**
     * 清理文件
     * */
    public static void cleanFile(File file){
        if (file == null){
            return;
        }
        if (file.isDirectory()){
            File[] files = file.listFiles();
            for (File subFile : files){
                cleanFile(subFile);
            }
        }else{
            file.delete();
        }
    }

}
